﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using DevelopTool.Bll.ChatBlls;
using DevelopTool.Common;
using DevelopTool.Model.ChatModels;
using DevelopTool.Model.Enums;
using Sunny.UI;

namespace DevelopTool.Forms.ChatForms.MessageItemControls
{
    /// <summary>
    /// 文件消息控件
    /// </summary>
    public partial class MessageItem_File : MessageItemBase
    {
        private ChatRecord chatRecord;

        private Action<ChatRecord> action;

        private ChatBll chatBll;

        private CancellationTokenSource sendFileCTS;

        public MessageItem_File(ChatRecord chatRecord)
        {
            InitializeComponent();

            this.chatRecord = chatRecord;
        }


        private void MessageItem_Filel_Load(object sender, EventArgs e)
        {
            this.chatBll = new ChatBll();

            ChatBll.ChatNewMessageEvent += ChatBll_ChatNewMessageEvent;

            this.Disposed += this.MessageItem_File_Disposed;

            this.uiToolTip.SetToolTip(this.btnSendControl, this.btnSendControl.TipsText);

            ThemHelper.SetSystemThem(this);

            if (!string.IsNullOrEmpty(chatRecord.ChatFileMetaData.FileLocalPath) && File.Exists(chatRecord.ChatFileMetaData.FileLocalPath))
            {
                this.FileIcon.Image = IconHelper.GetFileIcon(chatRecord.ChatFileMetaData.FileLocalPath, false).ToBitmap();
            }
            else
            {
                this.FileIcon.Image = IconHelper.GetFileIcon(Setting.System.DbFilePath, false).ToBitmap();
            }


            this.lblFileName.Text = chatRecord.ChatFileMetaData.FileName;
            this.processTransmit.Value = chatRecord.ChatFileMetaData.Progres;


            if (chatRecord.SendUser.UserId == Setting.Chat.UserId)
            {
                this.FileIcon.BackColor = Setting.Theme.BackColor;

                this.lblFileName.BackColor = Setting.Theme.BackColor;
                this.lblFileName.ForeColor = Color.Black;

                this.btnSendControl.LightColor = Setting.Theme.BackColor;
                this.btnSendControl.BackColor = Setting.Theme.BackColor;
                this.btnSendControl.RectColor = Color.LightGray;


                this.processTransmit.FillColor = Color.Black;
                this.processTransmit.BackColor = Setting.Theme.BackColor;
                this.processTransmit.ForeColor = Setting.Theme.BackColor;
                this.processTransmit.RectColor = Setting.Theme.BackColor;

                this.pnlBottom.RectColor = Color.Silver;

                if (this.chatRecord.SendState != ChatMessageSendState.Success)
                {
                    this.btnSendControl.TipsText = "重新发送";
                    this.uiToolTip.SetToolTip(this.btnSendControl, this.btnSendControl.TipsText);
                    this.btnSendControl.Symbol = 561523;
                }
            }
            else
            {
                this.FileIcon.BackColor = Color.Silver;

                this.lblFileName.BackColor = Color.Silver;
                this.lblFileName.ForeColor = Color.Black;

                this.btnSendControl.LightColor = Color.Silver;
                this.btnSendControl.BackColor = Color.Silver;
                this.btnSendControl.RectColor = Color.WhiteSmoke;

                this.btnSendControl.FillHoverColor = Color.Gray;


                this.processTransmit.FillColor = Color.Black;
                this.processTransmit.BackColor = Color.Silver;
                this.processTransmit.ForeColor = Color.White;
                this.processTransmit.RectColor = Color.Silver;

                this.pnlBottom.RectColor = Color.Gainsboro;
            }

            //接收进度100%时，隐藏底部进度条
            if (this.chatRecord.ChatFileMetaData.Progres >= 100)
            {
                this.pnlBottom.Visible = false;
            }
        }


        /// <summary>
        /// 接收文件
        /// </summary>
        /// <param name="chatFileMetaData"></param>
        private void ChatBll_ChatNewMessageEvent(ChatRecord chatRecord)
        {
            if (chatRecord.ChatFileMetaData != null && chatRecord.ChatFileMetaData.FileId == this.chatRecord.ChatFileMetaData.FileId)
            {
                this.chatRecord = chatRecord;
                this.Invoke(new Action(() =>
                {
                    //设置接收进度
                    this.processTransmit.Value = chatRecord.ChatFileMetaData.Progres;

                    //文件接收完成，设置文件图标
                    if (!string.IsNullOrEmpty(chatRecord.ChatFileMetaData.FileLocalPath) && File.Exists(chatRecord.ChatFileMetaData.FileLocalPath))
                    {
                        this.lblFileName.Text = chatRecord.ChatFileMetaData.FileName;
                        this.FileIcon.Image = IconHelper.GetFileIcon(chatRecord.ChatFileMetaData.FileLocalPath, false).ToBitmap();

                        this.pnlBottom.Visible = false;
                    }

                }));
            }
        }


        public override void Send(Action<ChatRecord> action)
        {
            this.sendFileCTS?.Cancel();
            this.sendFileCTS = new CancellationTokenSource();

            this.backgroundWorker_SendFile.RunWorkerAsync(this.chatRecord);

            this.action = action;

            base.Send(action);
        }


        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker_SendFile_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var chatRecord = (ChatRecord)e.Argument;

            try
            {
                chatRecord = chatBll.SendFile(chatRecord, this.sendFileCTS, progress =>
                   {
                       int pro = progress.ToInt();

                       //保存传输进度
                       chatRecord.ChatFileMetaData.Progres = pro;
                       this.chatBll.SaveChatRecord(chatRecord);

                       //报告传输进度
                       this.backgroundWorker_SendFile.ReportProgress(pro);
                   });
            }
            catch (Exception ex)
            {
                chatRecord.SendState = ChatMessageSendState.SendError;
                chatRecord.SendResult = ex.Message;
            }

            e.Result = chatRecord;
        }


        private void backgroundWorker_SendFile_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            //设置传输进度
            this.processTransmit.Value = e.ProgressPercentage;
        }


        private void backgroundWorker_SendFile_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            var chatRecord = (ChatRecord)e.Result;

            if (chatRecord.SendState == ChatMessageSendState.Success)
            {
                this.pnlBottom.Visible = false;
            }
            else
            {
                this.btnSendControl.Visible = true;
                this.btnSendControl.TipsText = "重新发送";
                this.uiToolTip.SetToolTip(this.btnSendControl, this.btnSendControl.TipsText);
                this.btnSendControl.Symbol = 561523;

                UIMessageTip.ShowError(this, chatRecord.SendResult);
            }

            this.chatBll.SaveChatRecord(chatRecord);

            this.action?.Invoke(chatRecord);
        }

        private void MessageItem_File_Disposed(object sender, EventArgs e)
        {
            ChatBll.ChatNewMessageEvent -= this.ChatBll_ChatNewMessageEvent;
            this.backgroundWorker_SendFile.CancelAsync();
        }


        private void btnSendControl_Click(object sender, EventArgs e)
        {
            if (this.btnSendControl.TipsText == "取消发送")
            {
                this.sendFileCTS?.Cancel();
            }
            else if (this.btnSendControl.TipsText == "重新发送")
            {
                this.btnSendControl.TipsText = "取消发送";
                this.uiToolTip.SetToolTip(this.btnSendControl, this.btnSendControl.TipsText);
                this.btnSendControl.Symbol = 361453;

                this.sendFileCTS = new CancellationTokenSource();

                this.backgroundWorker_SendFile.RunWorkerAsync(this.chatRecord);
            }

        }


        #region 右键菜单

        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!File.Exists(this.chatRecord.ChatFileMetaData.FileLocalPath))
            {
                UIMessageTip.ShowWarning(this, "文件已移动或已删除");
                return;
            }

            string filter = "所有格式|*.*";
            string fileName = this.chatRecord.ChatFileMetaData.FileLocalPath;

            FileInfo fileInfo = new FileInfo(this.chatRecord.ChatFileMetaData.FileLocalPath);

            if (Path.HasExtension(this.chatRecord.ChatFileMetaData.FileLocalPath))
            {
                filter = fileInfo.Extension.ToUpper().Replace(".", "") + "|*" + fileInfo.Extension;
            }

            if (!Dialogs.SaveFileDialog(ref fileName, filter)) return;
            if (string.IsNullOrEmpty(fileName)) return;

            fileInfo.CopyTo(fileName, true);//复制文件到选定路径

            UIMessageTip.ShowOk(this, "文件已另存");
        }

        private void 在文件中显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dialogs.OpenDir(this.chatRecord.ChatFileMetaData.FileLocalPath);
        }


        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!UIMessageBox.ShowMessageDialog($"是否确定删除此聊天消息？", $"{GlobalData.AppName_zh}-重要操作", true, UIStyle.Orange, false)) return;

            chatBll.DeleteSingleRecord(this.chatRecord);
        }

        private void 用开发助手打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileHelper.LocalOpenFile(this.chatRecord.ChatFileMetaData.FileLocalPath);
        }

        private void 用系统默认程序打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start(this.chatRecord.ChatFileMetaData.FileLocalPath);
        }

        #endregion 右键菜单

        /// <summary>
        /// 双击聊天文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MessageItem_File_DoubleClick(object sender, EventArgs e)
        {
            //用系统默认程序打开
            Process.Start(this.chatRecord.ChatFileMetaData.FileLocalPath);
        }

    }
}
